package com.cakemallproject.controller;

import com.cakemallproject.pojo.Result;
import com.cakemallproject.pojo.mapperObj.User;
import com.cakemallproject.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private UsersService usersService;

    @GetMapping
    public Result list() {
        log.info("获取用户列表");
        List<User> list = usersService.list();
        return Result.success(list);
    }

    @PostMapping
    public Result insert(@RequestBody User user) {
        log.info("添加用户：{}",user);
        try {
            usersService.insert(user);
        } catch (RuntimeException e) {
            return Result.error("username_exist");
        }
        return Result.success();
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids) {
        log.info("删除用户：{}",ids);
        usersService.delete(ids);
        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody User user) {
        log.info("更新用户：{}",user);
        try {
            usersService.update(user);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return Result.error("username_exist");
        }
        return Result.success();
    }


}
